﻿using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.ExSugar.UnitOfWork;
using RuoVea.ExUtil;
using RuoVea.ExUtil.Exceptions;
using RuoVea.OmiApi.Reports.Dto;
using RuoVea.OmiApi.Reports.Language;
using RuoVea.OmiApi.Reports.Models;
using RuoVea.OmiApi.Reports.Util;

namespace RuoVea.OmiApi.Reports.Service;

/// <summary>
/// 数据源
/// </summary>

[ApiExplorerSettings(GroupName = "Report")]
public partial class RptDatabaseService : IApplicationService
{
    /// <summary>
    /// 
    /// </summary>
    private readonly SugarRepository<RptDatabase> _thisRepository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisRepository"></param>
    public RptDatabaseService(SugarRepository<RptDatabase> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public RptDatabase GetDataById(long? id)
    {
        return _thisRepository.GetById(id);
    }

    /// <summary>
    ///  获取数据库类型
    ///  数据库类型 MySql = 0, SqlServer = 1, Sqlite = 2, Oracle = 3, PostgreSQL = 4,
    /// </summary>
    /// <returns></returns>
    public RestfulResult GetDataType()
    {
        var en = EnumExtension.GetDic<SqlSugar.DbType>(); ;
        var list = en.Where(it => it.Value < 5).Select(v => new { Value = v.Value.ToString(), Label = v.Key }).ToList();
        return Restful.Success(list);
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult<PageResult<RptDatabase>>> GetPagesAsync(RptDatabaseParam? data)
    {
        var restful = new RestfulResult<PageResult<RptDatabase>>() { Code = CodeStatus.OK };
        data ??= new RptDatabaseParam { PageNo = 1, PageSize = 10 };
        var query = await _thisRepository.AsQueryable()
               .WhereIF(data.Name.NotNullOrWhiteSpace(), u => u.Name.Contains(data.Name))
            .ToPageAsync(data.PageNo, data.PageSize);

        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 所有
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<RptDatabase>>> GetlistAsync()
    {
        var restful = new RestfulResult<PageResult<RptDatabase>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 100 };
        var query = await _thisRepository.AsQueryable()
             .Select(u => new RptDatabase
             {
                 Id = u.Id,
                 //Code = u.Code,
                 Name = u.Name
             })
            .ToPageAsync(data.PageNo, data.PageSize);
        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<RestfulResult> AddAsync(RptDatabase data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        var isExist = await _thisRepository.IsAnyAsync(u => u.Name == data.Name);
        if (isExist)
            return Restful.Bad(CodeStatus.BadRequest, i18n.data_duplicate);

        bool result = await _thisRepository.InsertAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.add}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync(RptDatabase data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        var isExist = await _thisRepository.IsAnyAsync(u => u.Name == data.Name && u.Id != data.Id);
        if (isExist)
            return Restful.Bad(CodeStatus.BadRequest, i18n.data_duplicate);

        bool result = await _thisRepository.UpdateAsync(data, true, true, $"{i18n.modify}");
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.modify}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns> 
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (data.Id == 0)
        {
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
        bool isDelete = await _thisRepository.DeleteByIdAsync(data.Id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.success}";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 测试链接
    /// </summary>
    /// <param name="connStr"></param>
    /// <param name="dbType"></param>
    /// <returns></returns>
    /// <exception cref="ParamiterException"></exception>
    public bool GetTestDbConnection(string connStr, int dbType)
    {
        using (var db = DbProvider.GetSugarDbContextBySelected(connStr, dbType))
        {
            db.Open();
        }
        return true;
    }

    /// <summary>
    /// 查询数据库配置信息列表
    /// </summary>
    /// <returns></returns>
    public object GetConnectionOptions()
    {
        var response = _thisRepository.AsQueryable()
            .Where(it=>it.IsEnabled== YesOrNot.Y)
            .Select(it => new
            {
                it.Id,
                it.Name
            })
            .ToList();
        return response;
    }
}